package com.sc.test.asynctask;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.sc.test.R;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Shen Chao
 * Created by 2019-02-18
 */
public class AsyncTaskActivity extends AppCompatActivity {
    @BindView(R.id.pb1)
    ProgressBar pb1;
    @BindView(R.id.pb2)
    ProgressBar pb2;
    @BindView(R.id.iv)
    ImageView iv;

    private ProgressDialog progressDialog;

    private String url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1550468908242&di=48b779b79168a94b30b3036ff1b084aa&imgtype=0&src=http%3A%2F%2Fwww.pptbz.com%2Fpptpic%2FUploadFiles_6909%2F201203%2F2012031220134655.jpg";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asynctask);
        ButterKnife.bind(this);
        pb1.setVisibility(View.GONE);
        pb2.setVisibility(View.GONE);
    }

    @OnClick(R.id.btn_load_image)
    public void onViewClicked() {
        progressDialog = new ProgressDialog(this);
        //设置标题
        progressDialog.setTitle("提示");
        //设置显示的信息
        progressDialog.setMessage("亲、正在玩命儿加载...请稍后...");
        //设置弹出框为水平进度加载模式
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        new MyAsyncTask().execute(url);

        //创建线程访问的方法
//        new Thread(){
//            @Override
//            public void run() {
//                String urlStr = "http://106.12.192.40:8080/tomcat.png";
//                try {
//                    URL url = new URL(urlStr);
//                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                    conn.setReadTimeout(3000);
//                    conn.setConnectTimeout(3000);
//                    int code = conn.getResponseCode();
//                    if (200 == code) {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(AsyncTaskActivity.this, "访问成功", Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                    }
//                } catch (MalformedURLException e) {
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }

    class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            iv.setImageBitmap(null);
            pb1.setVisibility(View.VISIBLE);
            pb2.setVisibility(View.VISIBLE);
            progressDialog.show();
            progressDialog.setCanceledOnTouchOutside(false);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            pb2.setProgress(values[0]);
            progressDialog.setProgress(values[1]);
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            String urlString = strings[0];
            Bitmap bitmap = null;
            InputStream is;
            ByteArrayOutputStream bos;
            try {
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setReadTimeout(3000);
                int lenth = conn.getContentLength();
                //设置最大值
                progressDialog.setMax(lenth);
                conn.connect();
                if (conn.getResponseCode() == 200) {
                    is = conn.getInputStream();
                    int len = 0;
                    int current = 0;
                    byte[] bytes = new byte[1024];
                    bos = new ByteArrayOutputStream();
                    while ((len = is.read(bytes)) != -1) {
                        Thread.sleep(200);
                        //追加进度
                        current += len;
                        //计算进度
                        int progress = (int) (current / (float) lenth * 100);
                        bos.write(bytes, 0, len);
                        publishProgress(progress, current);
                    }
                    byte[] bitmapBytes = bos.toByteArray();
                    bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            pb1.setVisibility(View.GONE);
            pb2.setVisibility(View.GONE);
            progressDialog.dismiss();
            iv.setImageBitmap(bitmap);
        }
    }
}
